package org.devio.takephoto.uitl;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.app.Context;
import ohos.app.Environment;
import ohos.data.resultset.ResultSet;
import ohos.media.photokit.metadata.AVStorage;
import ohos.utils.net.Uri;
import org.devio.takephoto.model.TException;
import org.devio.takephoto.model.TExceptionType;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;


/**
 * Uri解析工具类
 * Author: JPH
 * Date: 2015/8/26 0026 16:23
 */
public class TUriParse {
    private static final String TAG = TUriParse.class.getName();

    public static Uri convertFileUriToFileProviderUri(Context context, Uri uri) {
        if (uri == null) {
            return null;
        }
        if (uri.getScheme().equals("file")) {
            return getUriForFile(context, new File(uri.getDecodedPath()));
        }
        return uri;

    }

    public static Uri getTempUri(Context context) {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        File file = new File(Environment.DIRECTORY_PICTURES, "/images/" + timeStamp + ".jpg");
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        return getUriForFile(context, file);
    }

    public static Uri getTempUri(Context context, String path) {
        File file = new File(path);
        return getTempUri(context, file);
    }

    private static Uri getTempUri(Context context, File file) {
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        return getUriForFile(context, file);
    }

    private static Uri getUriForFile(Context context, File file) {
        return Uri.getUriFromFile(file);
    }

    public static String parseOwnUri(Context context, Uri uri) {
        if (uri == null) {
            return null;
        }
        String path = null;
        if (TextUtils.equals(uri.getDecodedAuthority(), TConstant.getFileProviderName(context))) {
            try {
                path = new File(uri.getDecodedPath().replace("camera_photos/", "")).getCanonicalPath();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            path = uri.getDecodedPath();
        }
        return path;
    }

    public static String getFilePathWithUri(Uri uri, Ability activity) throws TException {
        if (uri == null) {
            throw new TException(TExceptionType.TYPE_URI_NULL);
        }
        File picture = getFileWithUri(uri, activity);
        String picturePath = picture == null ? null : picture.getPath();
        if (TextUtils.isEmpty(picturePath)) {
            throw new TException(TExceptionType.TYPE_URI_PARSE_FAIL);
        }
        if (!TImageFiles.checkMimeType(activity, TImageFiles.getMimeType(activity, uri))) {
            throw new TException(TExceptionType.TYPE_NOT_IMAGE);
        }
        return picturePath;
    }

    static File getFileWithUri(Uri uri, Ability activity) {
        String picturePath = null;
        String scheme = uri.getScheme();
        if (scheme.equals("content")) {
            String[] filePathColumn = {AVStorage.Images.Media.DATA};
            DataAbilityHelper dataAbilityHelper = DataAbilityHelper.creator(activity, uri);
            ResultSet cursor = null;
            try {
                cursor = dataAbilityHelper.query(uri, filePathColumn, null);
            } catch (DataAbilityRemoteException e) {
                e.printStackTrace();
            }
            cursor.goToFirstRow();
            int columnIndex = cursor.getColumnIndexForName(filePathColumn[0]);
            if (columnIndex >= 0) {
                picturePath = cursor.getString(columnIndex);  //获取照片路径
            } else if (TextUtils.equals(uri.getDecodedAuthority(), TConstant.getFileProviderName(activity))) {
                picturePath = parseOwnUri(activity, uri);
            }
            cursor.close();
        } else if (scheme.equals("file")) {
            picturePath = uri.getDecodedPath();
        }
        return TextUtils.isEmpty(picturePath) ? null : new File(picturePath);
    }

    public static String getFilePathWithDocumentsUri(Uri uri, Ability activity) throws TException {
        if (uri == null) {
            return null;
        }
        if (uri.getScheme().equals("content") && uri.getDecodedPath().contains("document")) {
            File tempFile = TImageFiles.getTempFile(activity, uri);
            try {
                return tempFile.getPath();
            } catch (Exception e) {
                e.printStackTrace();
                throw new TException(TExceptionType.TYPE_NO_FIND);
            }
        } else {
            return getFilePathWithUri(uri, activity);
        }
    }
}
